import 'package:flutter/material.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/cupertino.dart';
import 'package:share/share.dart';
import '../Video/BottomInput.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

Dio dio = new Dio();

class VideoPage extends StatefulWidget {
  final msg;
  VideoPage({Key key, @required this.msg}) : super(key: key);
  _VideoPageState createState() => _VideoPageState(this.msg);
}

class _VideoPageState extends State<VideoPage> {
  final msg;
  var cang;
  String backResult;
  void shoucang() async {
    //收藏
    if (number.length == 10) {
      Response response = await dio.get(
        'http://xssw.gdit.edu.cn/sizheng/api/v1/collect?query={"studentId":"${user_id}","video":"${msg['_id']}"}');
    cang = response.data;
    }else{
      Response response = await dio.get(
        'http://xssw.gdit.edu.cn/sizheng/api/v1/collect?query={"teacherId":"${user_id}","video":"${msg['_id']}"}');
    cang = response.data;
    }
    setState(() {});
  }

  String user_id;
  var number;
  getName() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    user_id = sharedPreferences.getString('user_id');
    number = sharedPreferences.getString('number');
    shoucang(); // 初始化根据ID拉取收藏数据11
    setState(() {});
  }

  var _res;
  void message() async {
    //评论
    Response response = await dio.get(
        'http://xssw.gdit.edu.cn/sizheng/api/v1/Comment?query={"videoId":"${msg['_id']}"}&sort=-createAt');
    _res = response.data;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    message();
    getName();
  }




  _VideoPageState(this.msg);
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          message();
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Scaffold(
          appBar: AppBar(),
          body: ListView(
            physics: const NeverScrollableScrollPhysics(),
            children: <Widget>[
              Container(
                height: 200,
                child: 
                PlayPage(
                  msg: this.msg,
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height - 330,
                child: ListView(shrinkWrap: true, children: <Widget>[
                  Container(
                      //标题
                      margin:
                          EdgeInsets.only(left: 15.0, right: 15.0, top: 10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            "${msg['title']}",
                            style: TextStyle(fontSize: 18.0),
                          ),
                          Row(
                            children: <Widget>[
                              Container(
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  '${msg['from']}',
                                  style: TextStyle(
                                      fontSize: 14.0, color: Colors.grey),
                                ),
                              ),
                              Container(
                                padding: EdgeInsets.all(10),
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  '${msg['createdAt'].substring(0, 10)}',
                                  style: TextStyle(
                                      fontSize: 14.0, color: Colors.grey),
                                ),
                              ),
                            ],
                          ),
                        ],
                      )),
                  // Container(
                  //   //简介
                  //   margin: EdgeInsets.only(left: 5.0, right: 10.0, top: 10.0),
                  //   child: Column(
                  //     crossAxisAlignment: CrossAxisAlignment.start,
                  //     children: <Widget>[
                  //       Row(
                  //         children: <Widget>[
                  //           Text("丨",
                  //               style: TextStyle(
                  //                   fontSize: 25.0,
                  //                   color: Colors.red,
                  //                   fontWeight: FontWeight.w900)),
                  //           Text(
                  //             "简介",
                  //             style: TextStyle(fontSize: 18.0),
                  //           )
                  //         ],
                  //       ),
                  //       Container(
                  //         margin: EdgeInsets.all(10),
                  //         child: Text(
                  //           "简介内容评论内容评论内容评论内容评论内容评论内容评论内容",
                  //           style: TextStyle(
                  //               fontSize: 16.0, color: Colors.grey[600]),
                  //         ),
                  //       ),
                  //     ],
                  //   ),
                  // ),
                  Container(
                    //评论
                    margin: EdgeInsets.only(left: 5.0, right: 10.0, top: 10.0),
                    child: Row(
                      children: <Widget>[
                        Text("丨",
                            style: TextStyle(
                                fontSize: 25.0,
                                color: Colors.red,
                                fontWeight: FontWeight.w900)),
                        Text(
                          "评论",
                          style: TextStyle(fontSize: 18.0),
                        )
                      ],
                    ),
                  ),
                  _res == null
                      ? Container(
                          margin: EdgeInsets.fromLTRB(0, 50, 0, 0),
                          alignment: Alignment.center,
                          child: Text(
                            '暂无评论',
                            style: TextStyle(fontSize: 18.0),
                          ),
                        )
                      : _res.length == 0
                          ? Container(//没有评论
                              margin: EdgeInsets.fromLTRB(0, 50, 0, 0),
                              alignment: Alignment.center,
                              child: Text(
                                '暂无评论',
                                style: TextStyle(fontSize: 18.0),
                              ),
                            )
                          : Container(//有评论
                              // margin: EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
                              child: ListView.builder(
                                itemCount: _res.length,
                                shrinkWrap: true,
                                physics: const NeverScrollableScrollPhysics(),
                                itemBuilder: (context, index) {
                                  return ListTile(
                                      title: Row(
                                        children: <Widget>[
                                          Container(
                                              width: 30.0,
                                              height: 30.0,
                                              decoration: ShapeDecoration(
                                                  shape: CircleBorder(),
                                                  image: DecorationImage(
                                                      fit: BoxFit.cover,
                                                      image: AssetImage(
                                                        "images/head.jpg",
                                                      )))),
                                          
                                          Container(
                                            margin: EdgeInsets.only(
                                                left: 10, bottom: 10),
                                            child: Text(
                                              '${_res[index]['name']}',
                                      style: TextStyle(
                                          color: Colors.red,
                                          fontSize: 15),
                                            ),
                                          ),
                                           _res[index]['userId'] == user_id
                                              ? Container(
                                            width: 30,
                                            height: 16,
                                            alignment: Alignment.center,
                                            decoration: BoxDecoration(
                                              borderRadius: BorderRadius.circular(15),
                                              color: Colors.blue,
                                              ),
                                            margin: EdgeInsets.only(
                                                left: 10, bottom: 10),
                                            child: Text("我",style: TextStyle(fontSize: 12,color: Colors.white),),
                                          )
                                          : Container()
                                        ],
                                      ),
                                      subtitle: Column(
                                        children: <Widget>[
                                          Container(
                                            width: MediaQuery.of(context).size.width *4/5,
                                            margin: EdgeInsets.only(
                                              left: 40,
                                              right: 20,
                                            ),
                                            padding:
                                                EdgeInsets.only(bottom: 10),
                                            child: Text(
                                              "${_res[index]['contain']}",
                                              style: TextStyle(
                                                  fontSize: 16.0,
                                                  color: Colors.black),
                                            ),
                                          ),
                                          _res[index]['userId'] == user_id
                                              ? Container(//删除按钮
                                                  width: MediaQuery.of(context)
                                                      .size
                                                      .width,
                                                  alignment:
                                                      Alignment.centerLeft,
                                                  padding: EdgeInsets.only(
                                                      left: 40.0,bottom: 5.0),
                                                  child: InkWell(
                                                    child: Text(
                                                      '删除',
                                                      style: TextStyle(
                                                          fontSize: 14.0,
                                                          decoration:
                                                              TextDecoration
                                                                  .underline),
                                                    ),
                                                    onTap: () async {
                                                      Dio dio = new Dio();
                                                      showDialog<Null>(
                                                        context: context,
                                                        barrierDismissible:
                                                            false,
                                                        builder: (BuildContext
                                                            context) {
                                                          return new AlertDialog(
                                                            content:
                                                                new SingleChildScrollView(
                                                              child:
                                                                  new ListBody(
                                                                children: <
                                                                    Widget>[
                                                                  new Text(
                                                                      '是否删除该条评论'),
                                                                ],
                                                              ),
                                                            ),
                                                            actions: <Widget>[
                                                              new Row(
                                                                children: <Widget>[
                                                                  FlatButton(
                                                                child: new Text(
                                                                    '确定'),
                                                                onPressed:
                                                                    () async {
                                                                  Response
                                                                      response =
                                                                      await dio
                                                                          .delete(
                                                                    "http://xssw.gdit.edu.cn/sizheng/api/v1/Comment/" +
                                                                        '${_res[index]['_id']}',
                                                                  );
                                                                  message();
                                                                  Navigator.of(
                                                                          context)
                                                                      .pop();
                                                                },
                                                              ),FlatButton(
                                                                child: new Text(
                                                                    '取消'),
                                                                onPressed:
                                                                    () {
                                                                  Navigator.of(
                                                                          context)
                                                                      .pop();
                                                                },
                                                              ),
                                                                ],
                                                              )
                                                            ],
                                                          );
                                                        },
                                                      );
                                                    },
                                                  ))
                                              : Container(),
                                          Container(
                                            decoration: BoxDecoration(
                                                border: Border(
                                                    bottom: BorderSide(
                                                        width: 1,
                                                        color: Color(
                                                            0xffe5e5e5)))),
                                          )
                                        ],
                                      ));
                                },
                              ),
                            )
                ]),
              )
            ],
          ),
          bottomNavigationBar: BottomAppBar(//底部栏
            child: Container(
                height: 50.0,
                width: MediaQuery.of(context).size.width,
                // margin: EdgeInsets.only(left: 30.0,right: 30.0),
                // child: SingleChildScrollView(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                        width: MediaQuery.of(context).size.width * 2 / 3,
                        child: Container(
                            color: Colors.grey[300],
                            margin: EdgeInsets.all(10),
                            padding: EdgeInsets.fromLTRB(15, 7, 10, 7),
                            height: 30,
                            child: InkWell(
                              child: Text("欢迎发表你的评论"),
                              onTap: () async {
                                // message();
                                await Navigator.push(
                                        context,
                                        PopRoute(
                                            child: BottomInputDialog(
                                                videoId: '${msg['_id']}')))
                                    .then((userInfo) {
                                  setState(() {
                                    backResult = userInfo;
                                    if (backResult.length > 0) {
                                      message();
                                      showDialog<Null>(
                                        context: context,
                                        barrierDismissible: false,
                                        builder: (BuildContext context) {
                                          return new AlertDialog(
                                            content: new SingleChildScrollView(
                                              child: new ListBody(
                                                children: <Widget>[
                                                  new Text('评论发表成功'),
                                                ],
                                              ),
                                            ),
                                            actions: <Widget>[
                                              new FlatButton(
                                                child: new Text('确定'),
                                                onPressed: () {
                                                  Navigator.of(context).pop();
                                                },
                                              ),
                                            ],
                                          );
                                        },
                                      );
                                    }
                                  });
                                });
                                print(backResult.isEmpty);
                              },
                            )
                            )),
                    Container(
                      child: Row(
                        // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                              // margin: EdgeInsets.fromLTRB(28.0, 0.0, 20.0, 0.0),
                              height: 40,
                              width: MediaQuery.of(context).size.width / 6,
                              child: InkWell(
                            child: Container(
                              alignment: Alignment.center,
                              child: cang != null
                                  ? Image.asset(
                                      cang.length != 0
                                          ? 'images/star2.png'
                                          : 'images/star1.png',
                                      width: 25,
                                      height: 25,
                                    )
                                  : Image.asset(
                                      'images/star1.png',
                                      width: 25,
                                      height: 25,
                                    ),
                            ),
                            onTap: () async {
                              //判断数组中是否已经收藏
                              if (number.length == 10) {
                                if (cang.length == 0) {
                                  Response response = await dio.post(
                                      "http://xssw.gdit.edu.cn/sizheng/api/v1/collect",
                                      data: {
                                        'studentId': '$user_id',
                                        'video': '${msg['_id']}'
                                      });
                                } else {
                                  Response response = await dio.delete(
                                      "http://xssw.gdit.edu.cn/sizheng/api/v1/collect/"+'${cang[0]['_id']}');
                                }
                                
                              }else{
                                if (cang.length == 0) {
                                  Response response = await dio.post(
                                      "http://xssw.gdit.edu.cn/sizheng/api/v1/collect",
                                      data: {
                                        'teacherId': '$user_id',
                                        'video': '${msg['_id']}'
                                      });
                                } else {
                                  Response response = await dio.delete(
                                      "http://xssw.gdit.edu.cn/sizheng/api/v1/collect/"+'${cang[0]['_id']}');
                                }
                              }
                             shoucang();
                              setState(() {});
                            },
                          )),
                          Container(
                              width: MediaQuery.of(context).size.width / 6,
                              height: 60.0,
                              child: InkWell(
                                child: Icon(
                                  Icons.share,
                                  size: 25.0,
                                  color: Colors.grey[800],
                                ),
                                onTap: () {
                                  Share.share('${msg['title']}'+'<<<<复制这段话后打开最新版【广科思政】');
                                },
                              )),
                        ],
                      ),
                    )
                  ],
                )
                // )
                ),
          ),
        ));
  }
}

class PlayPage extends StatefulWidget {
  final msg;
  PlayPage({Key key, @required this.msg}) : super(key: key);
  _PlayPageState createState() => _PlayPageState(this.msg);
}

class _PlayPageState extends State<PlayPage> {
  final msg;
  _PlayPageState(this.msg);
  final FijkPlayer player = FijkPlayer();

  @override
  void initState() {
    super.initState();
    player.setDataSource("${msg['contain']}", autoPlay: true);
  }

  @override
  void dispose() {
    super.dispose();
    player.release();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FijkView(
        player: player,
        color: Colors.grey,
        height: 205,
        width: MediaQuery.of(context).size.width,
      ),
    );
  }
}
